# -*- coding: utf-8 -*-
# @Time        :2025/7/7 下午3:11
# @Author      :文刀水寿
# @File        : xhs.py
"""
 @Description :
"""
import time
import random
from datetime import datetime
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import re


def setup_driver():
    """配置Chrome浏览器驱动"""
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # 无头模式，不显示浏览器窗口
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")  # 隐藏自动化特征
    chrome_options.add_argument("--window-size=1920,1080")
    chrome_options.add_argument(
        f"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

    # 设置ChromeDriver路径
    service = Service("path/to/chromedriver")  # 请替换为您的ChromeDriver路径
    driver = webdriver.Chrome(service=service, options=chrome_options)

    # 模拟人类行为
    driver.implicitly_wait(10)
    return driver


def login_xiaohongshu(driver):
    """登录小红书（如果需要）"""
    # 打开小红书首页
    driver.get("https://www.xiaohongshu.com/")

    # 等待页面加载
    time.sleep(random.uniform(3, 5))

    # 如果需要登录，这里可以添加登录逻辑
    # 例如：点击登录按钮，输入账号密码等
    # 注意：小红书可能有验证码，复杂登录可能需要人工干预

    print("已准备好爬取数据")
    return driver


def fetch_trending_topics(driver):
    """获取小红书热度榜数据"""
    # 打开小红书热度榜页面
    driver.get("https://www.xiaohongshu.com/explore/hot")

    # 等待页面加载完成
    try:
        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, ".hot-list-item"))
        )
    except Exception as e:
        print(f"页面加载超时: {e}")
        return []

    # 模拟滚动，加载更多内容
    for i in range(3):  # 滚动3次
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(random.uniform(2, 4))

    # 获取页面源码
    page_source = driver.page_source
    return page_source


def parse_trending_data(html_content):
    """解析热度榜数据"""
    soup = BeautifulSoup(html_content, 'html.parser')
    topics = []

    try:
        # 定位热度榜项目
        items = soup.select(".hot-list-item")

        for item in items:
            try:
                # 排名
                rank = item.select_one(".rank").text.strip()

                # 标题
                title = item.select_one(".title").text.strip()

                # 热度值
                hot_value = item.select_one(".hot-value").text.strip()

                # 链接
                link = "https://www.xiaohongshu.com" + item.select_one("a")["href"]

                # 标签（如果有）
                tags = [tag.text.strip() for tag in item.select(".tag")]

                topics.append({
                    "排名": rank,
                    "标题": title,
                    "热度值": hot_value,
                    "标签": tags,
                    "链接": link,
                    "抓取时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                })
            except Exception as e:
                print(f"解析单个项目失败: {e}")
                continue

    except Exception as e:
        print(f"解析热度榜失败: {e}")

    return topics


def save_to_excel(data, filename="小红书热度榜.xlsx"):
    """保存数据到Excel"""
    if not data:
        print("没有数据可保存")
        return False

    try:
        df = pd.DataFrame(data)
        df.to_excel(filename, index=False, sheet_name="热度榜")
        print(f"成功保存{len(data)}条数据到{filename}")
        return True
    except Exception as e:
        print(f"保存Excel失败: {e}")
        return False


def main():
    print("开始爬取小红书热度榜数据...")

    # 1. 初始化浏览器
    driver = setup_driver()

    try:
        # 2. 登录（如果需要）
        driver = login_xiaohongshu(driver)

        # 3. 获取热度榜内容
        html_content = fetch_trending_topics(driver)

        # 4. 解析数据
        topics = parse_trending_data(html_content)
        print(f"成功获取{len(topics)}条热度榜数据")

        # 5. 保存到Excel
        if topics:
            today = datetime.now().strftime("%Y%m%d")
            filename = f"小红书热度榜_{today}.xlsx"
            save_to_excel(topics, filename)

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 关闭浏览器
        if driver:
            driver.quit()
            print("浏览器已关闭")


if __name__ == "__main__":
    main()
